﻿using System.Text.RegularExpressions;
using System.Web.Mvc;
using Smarly.Bussines.Model;
using Smarly.Bussines.Parsing;
using Smarly.Web.Controllers;
using Smarly.Web.Controllers.Base;

namespace Smarly.Web.Areas.Admin.Controllers
{
	public class EditContextController : BaseController
	{
		[HttpGet, ActionName("Index")]
		[AdminAuthorize(Roles = "Admin", EditorParam = "hashTag")]
		public ActionResult IndexGet(string hashTag, long textId)
		{
			BookTree t = new BookTree() { Id = textId }.Get(hashTag);
			string result = Regex.Replace(t.Text.ToBbCode(), @"\[pre=(.)+?](.|\s)+?\[/pre]", (m) => System.Net.WebUtility.HtmlDecode(m.Value).Replace("[br]", "\r\n"));
			return Json(new {Result = result, TextId = t.Id}, JsonRequestBehavior.AllowGet);
		}

		[HttpPost, ActionName("Index")]
		[AdminAuthorize(Roles = "Admin", EditorParam = "parentTag")]
		public ActionResult IndexPost(string parentTag, long afterTextId, string text)
		{
			text.ToText().Save(afterTextId, parentTag);;		
			return Json(new {});
		}

		[HttpPut, ActionName("Index")]
		[AdminAuthorize(Roles = "Admin", EditorParam = "hashTag")]
		public ActionResult IndexPut(string hashTag, string text)
		{
			text.ToText().Save(0, hashTag);
			return Json(new {});
		}

		[HttpDelete, ActionName("Index")]
		[AdminAuthorize(Roles = "Admin", EditorParam = "hashTag")]
		public ActionResult IndexDelete(string hashTag, long textId)
		{
			new BookTree {Id = textId}.Delete(hashTag);
			return Json(new {});
		}
	}
}
